<?php
/***********************************************************
 * 文章模型
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\admin\model\Article as Articlemodel;
class Article extends Base
{
    // 模型标识
    public $nid = 'article';
    // 模型ID
    public $channeltype = '';

    public $popedom = '';

    public function initialize() {
        parent::initialize();
        $gzpcfglobal = get_global();
        $channeltype_list = $gzpcfglobal['channeltype_list'];
        $this->channeltype = $channeltype_list[$this->nid];
        $this->assign('nid', $this->nid);
        $this->assign('channeltype', $this->channeltype);
        $this->assign('admin_info', session::get('admin_info'));
        $ctl_act = 'Content/index';
        $this->popedom = appfile_popedom($ctl_act);
    }

    // 文档列表
    public function index()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        $assign_data = array();
        $channel= input('param.channel/d', 0);//文档栏目id
        $typeid = input('param.typeid/d', 0); //文档分类栏目id
        $keywords = input('param.keywords', ''); //搜所
        $this->assign('channel', $channel);
        $this->assign('typeid', $typeid);
        $this->assign('keywords', $keywords);
        if (Request::isAjax()) {
            $Articlemodel = new Articlemodel();
            return $Articlemodel->tableData(input('param.'));
        }
        // 允许发布文档列表的栏目
        $arctype_html = allow_release_arctype($typeid, [$this->channeltype]);
        $typeidNum = substr_count($arctype_html, '</option>');
        $assign_data['arctype_html'] = $arctype_html;
        $assign_data['typeidNum'] = $typeidNum;
        $this->assign($assign_data);
        return $this->fetch();
    }

    // 添加
    public function add()
    {
        $where=[];
        $result = ['status' => false,'msg' => '失败','data' => '','url' => ''];
        $gzpcfglobal = get_global();
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["add"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('post.');
            $typeid = input('post.typeid/d', 0);
            if (empty($typeid)) {
                $result['status'] = false;
                $result['msg']    = "请选择所属栏目！";
                return $result;
            }
            // 根据标题自动提取相关的关键字
            $seo_keywords = $post['seo_keywords'];
            if (!empty($seo_keywords)) {
                $seo_keywords = str_replace('，', ',', $seo_keywords);
            }
            // 是否有封面图
            if (empty($post['litpic'])) {
                $is_litpic = 0; // 无封面图
            } else {
                $is_litpic = 1; // 有封面图
            }
            // 外部链接跳转
            $jumplinks = '';
            $is_jump = isset($post['is_jump']) ? $post['is_jump'] : 0;
            if (intval($is_jump) > 0) {
                $jumplinks = $post['jumplinks'];
            }
            // 模板文件，如果文档模板名与栏目指定的一致，默认就为空。让它跟随栏目的指定而变
            if ($post['type_tempview'] == $post['tempview']) {
                unset($post['type_tempview']);
                unset($post['tempview']);
            }else{
                unset($post['type_tempview']);
            }
            // 存储数据
            $newData = array(
                'typeid'=> $typeid,
                'channel'   => $this->channeltype,
                'is_b'      => empty($post['is_b']) ? 0 : $post['is_b'],
                'is_head'      => empty($post['is_head']) ? 0 : $post['is_head'],
                'is_special'      => empty($post['is_special']) ? 0 : $post['is_special'],
                'is_recom'      => empty($post['is_recom']) ? 0 : $post['is_recom'],
                'is_jump'     => $is_jump,
                'is_litpic'     => $is_litpic,
                'jumplinks' => $jumplinks,
                'seo_keywords'     => $seo_keywords,
                'seo_description'     => $post['seo_description'],
                'admin_id'  => session::get('admin_id'),
                'sort_order'    => 100,
                'add_time'     => strtotime($post['add_time']),
                'update_time'  => strtotime($post['add_time']),
                'show_time'      => getTime(),
            );
            $data = array_merge($post, $newData);
            unset($data['file']);
            $data1 = array_merge($post, $newData);
            unset($data1['file'],$data1['addonFieldExt']);
            $aid = Db::name('archives')->insertGetId($data1);
            if ($aid) {
                $pcfarticle = new Articlemodel;
                $pcfarticle->afterSave($aid, $data, 'add');
                $result['status'] = true;
                $result['msg']    = "操作成功";
                $result['url']    = url('/index/uphtml')->suffix('html')->domain(true)->build().'?aid='.$aid.'&tid='.$typeid.'&channel='.$this->channeltype.'&action='.Request::action();
                return $result;
            }
            $result['status'] = false;
            $result['msg']    = "操作失败";
            return $result;
        }
        $where[]=['current_channel','=',$this->channeltype];
        $where[]=['parent_id','=',0];
        $where[]=['status','=',1];
        $where[]=['is_del','=',0];
        $typeid = input('param.typeid/d', 0);
        if (empty($typeid)) {
            $arctypeInfo = Db::name('arctype')->where($where)->order('sort_order asc, id asc')->find();
            $typeid = $arctypeInfo['id'];
        } else {
            $arctypeInfo = Db::name('arctype')->find($typeid);
        }
        // 允许发布文档列表的栏目
        $arctype_html = allow_release_arctype($typeid, array($this->channeltype));
        $assign_data['arctype_html'] = $arctype_html;
        // 自定义字段
        $FieldLogic = new \app\admin\logic\FieldLogic;
        $addonFieldExtList = $FieldLogic->getChannelFieldList($this->channeltype);
        $channelfieldBindRow = Db::name('channelfield_bind')->where('typeid','IN', [0,$typeid])->column('field_id');
        if (!empty($channelfieldBindRow)) {
            foreach ($addonFieldExtList as $key => $val) {
                if (!in_array($val['id'], $channelfieldBindRow)) {
                    unset($addonFieldExtList[$key]);
                }
            }
        }
        $assign_data['addonFieldExtList'] = $addonFieldExtList;
        $assign_data['aid'] = 0;
        // 阅读权限
        $arcrank_list = get_arcrank_list();
        $assign_data['arcrank_list'] = $arcrank_list;
        // 模板列表
        $archivesLogic = new \app\admin\logic\ArchivesLogic;
        $templateList = $archivesLogic->getTemplateList($this->nid);
        $this->assign('templateList', $templateList);
        // 默认模板文件
        $tempview = 'view_'.$this->nid.'.'.config('view.view_suffix');
        !empty($arctypeInfo['tempview']) && $tempview = $arctypeInfo['tempview'];
        $this->assign('tempview', $tempview);
        $this->assign($assign_data);
        return $this->fetch();
    }

    // 编辑
    public function edit()
    {
        $pcfarticle = new Articlemodel;
        $gzpcfglobal = get_global();
        $result = ['status' => false,'msg' => '失败','data' => '','url' => ''];

        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }  
            $post = input('post.');
            $typeid = input('post.typeid/d', 0);
            $content = input('post.addonFieldExt.content', '', null);
            if (empty($typeid)) {
                $result['status'] = false;
                $result['msg']    = "请选择所属栏目！";
                return $result;
            }

            // 根据标题自动提取相关的关键字
            $seo_keywords = $post['seo_keywords'];
            if (!empty($seo_keywords)) {
                $seo_keywords = str_replace('，', ',', $seo_keywords);
            } 
            // 自动获取内容第一张图片作为封面图
            if (empty($post['litpic'])) {
                $post['litpic'] = get_html_first_imgurl($content);
            }
            // 是否有封面图
            if (empty($post['litpic'])) {
                $is_litpic = 0; // 无封面图
            } else {
                $is_litpic = !empty($post['is_litpic']) ? $post['is_litpic'] : 0; // 有封面图
            }
            // SEO描述
            $seo_description = '';
            if (empty($post['seo_description']) && !empty($content)) {
                $seo_description = @msubstr(checkStrHtml($content), 0, $gzpcfglobal['arc_seo_description_length'], false);
            } else {
                $seo_description = $post['seo_description'];
            }
            // 外部链接
            $jumplinks = '';
            $is_jump = isset($post['is_jump']) ? $post['is_jump'] : 0;
            if (intval($is_jump) > 0) {
                $jumplinks = $post['jumplinks'];
            }
            // 模板文件，如果文档模板名与栏目指定的一致，默认就为空。让它跟随栏目的指定而变
            if ($post['type_tempview'] == $post['tempview']) {
                unset($post['type_tempview']);
                unset($post['tempview']);
            }else{
                unset($post['type_tempview']);
            }
            // 同步栏目切换模型之后的文档模型
            $channel = Db::name('arctype')->where('id',$typeid)->value('current_channel');
            // 存储数据
            $newData = array(
                'typeid'=> $typeid,
                'channel'   => $channel,
                'is_b'      => empty($post['is_b']) ? 0 : $post['is_b'],
                'is_head'   => empty($post['is_head']) ? 0 : $post['is_head'],
                'is_special'=> empty($post['is_special']) ? 0 : $post['is_special'],
                'is_recom'  => empty($post['is_recom']) ? 0 : $post['is_recom'],
                'is_jump'   => $is_jump,
                'is_litpic' => $is_litpic,
                'jumplinks' => $jumplinks,
                'seo_keywords'     => $seo_keywords,
                'seo_description'     => $seo_description,
                'add_time'     => strtotime($post['add_time']),
                'update_time'     => getTime(),
            );
            $data = array_merge($post, $newData);
            unset($data['file']);
            $data1 = array_merge($post, $newData);
            unset($data1['file'],$data1['addonFieldExt'],$data1['aid']);
            $r = Db::name('archives')->where('aid', $data['aid'])->update($data1);

            if ($r) {
                $pcfarticle->afterSave($data['aid'], $data, 'edit');
                $result['status'] = true;
                $result['msg']    = "操作成功";
                $result['url']    = url('/index/uphtml')->suffix('html')->domain(true)->build().'?aid='.$data['aid'].'&tid='.$typeid.'&channel='.$this->channeltype.'&action='.Request::action();
                return $result;
            }
            $result['status'] = false;
            $result['msg']    = "操作失败";
            return $result;
        }

        $assign_data = array();
        $id = input('id/d');
        $info = $pcfarticle->getInfo($id, null, false);
        if (empty($info)) {
            return $this->contentNotice("数据不存在，请联系管理员！",url('/Article/index')->suffix(true)->domain(true)->build(),3,false);
        }
        $admin_info = session::get('admin_info');
        if (0 < intval($admin_info['role_id'])) {
            $auth_role_info = $admin_info['auth_role_info'];
            if(!empty($auth_role_info)){
                if(isset($auth_role_info['only_oneself']) && (1 == $auth_role_info['only_oneself']) && ($admin_info['admin_id'] != $info['admin_id'])){
                    return $this->contentNotice("您不能操作其他人文档",url('/Article/index')->suffix(true)->domain(true)->build(),3,false);
                }
            }
        }
        // 兼容采集没有归属栏目的文档
        if (empty($info['channel'])) {
            $channelRow = Db::name('channel_type')->field('id as channel')->where('id',$this->channeltype)->find();
            $info = array_merge($info, $channelRow);
        }
        $typeid = $info['typeid'];
        // 栏目信息
        $arctypeInfo = Db::name('arctype')->find($typeid);
        $info['channel'] = $arctypeInfo['current_channel'];
        // SEO描述
        if (!empty($info['seo_description'])) {
            $info['seo_description'] = @msubstr(checkStrHtml($info['seo_description']), 0, $gzpcfglobal['arc_seo_description_length'], false);
        }
        $assign_data['field'] = $info;
        // 允许发布文档列表的栏目
        $arctype_html = allow_release_arctype($typeid, array($this->channeltype));
        $assign_data['arctype_html'] = $arctype_html;
        // 自定义字段
        $FieldLogic = new \app\admin\logic\FieldLogic;
        $addonFieldExtList = $FieldLogic->getChannelFieldList($info['channel'], 0, $id, $info);
        $channelfieldBindRow = Db::name('channelfield_bind')->where('typeid','IN', [0,$typeid])->column('field_id');
        if (!empty($channelfieldBindRow)) {
            foreach ($addonFieldExtList as $key => $val) {
                if (!in_array($val['id'], $channelfieldBindRow)) {
                    unset($addonFieldExtList[$key]);
                }
            }
        }
        $assign_data['addonFieldExtList'] = $addonFieldExtList;
        $assign_data['aid'] = 0;
        // 阅读权限
        $arcrank_list = get_arcrank_list();
        $assign_data['arcrank_list'] = $arcrank_list;

        // 模板列表
        $archivesLogic = new \app\admin\logic\ArchivesLogic;
        $templateList = $archivesLogic->getTemplateList($this->nid);
        $this->assign('templateList', $templateList);

        // 默认模板文件
        if($info['tempview']){
            $tempview = $info['tempview'];
        }else{
            $tempview = 'view_'.$this->nid.'.'.config('view.view_suffix');
            !empty($arctypeInfo['tempview']) && $tempview = $arctypeInfo['tempview'];            
        }
        $this->assign('tempview', $tempview);
        $this->assign($assign_data);
        return $this->fetch();
    }
    
    // 删除
    public function del()
    {
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["delete"]){
                if(config('params.auth_msg.test')){
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['code' => 0, 'msg' => config('params.auth_msg.delete')];
                    return $result;                    
                }
            } 
            $archivesLogic = new \app\admin\logic\ArchivesLogic;
            return $archivesLogic->del();
        }
    }

}